#pragma once

#include "sock.hpp"
#include <functional>
#include <poll.h>

namespace poll_ns
{
    static const int defaultport = 8080;
    static const int num = 2048;
    static const int defaultfd = -1;

    using func_t = std::function<std::string(const std::string &)>;

    class PollServer
    {

    public:
        PollServer(func_t func, int port = defaultport) : _func(func), _port(port), _listensock(-1), _rfds(nullptr)
        {
        }
        void initServer()
        {
            _listensock = Sock::Socket();
            Sock::Bind(_listensock, _port);
            Sock::Listen(_listensock);
            logMessage(NORMAL, "_listensock : %d", _listensock);
            _rfds = new struct pollfd[num];
            for (int i = 0; i < num; ++i) ResetItem(i);
            _rfds[0].fd = _listensock;
            _rfds[0].events = POLLIN;
        }
        void Print()
        {
            std::cout << "fd list: " << std::endl;
            for (int i = 0; i < num; ++i)
            {
                if (_rfds[i].fd != defaultfd)
                    std::cout << _rfds[i].fd << " ";
            }
            std::cout << std::endl;
        }
        void HandlerEvent()
        {
            for (int i = 0; i < num; ++i)
            {
                // 过滤掉非法的fd
                if (_rfds[i].fd == defaultfd)
                    continue;

                if(!(_rfds[i].events & POLLIN)) continue;

                if (_rfds[i].fd == _listensock && (_rfds[i].revents & POLLIN))
                    Accepter(_listensock);
                else if (_rfds[i].revents & POLLIN)
                    Recver(i);
                else {}
            }
        }
        void ResetItem(int i)
        {
                _rfds[i].fd = defaultfd;
                _rfds[i].events = 0;
                _rfds[i].revents = 0;
        }
        void Accepter(int listensock)
        {
            std::string clientip;
            uint16_t clientport = 0;
            int sock = Sock::Accept(listensock, &clientip, &clientport);
            if (sock < 0)
                return;
            logMessage(NORMAL, "accept success [%s:%d]", clientip.c_str(), clientport);

            // 不一定有数据
            int i = 0;
            for (; i < num; i++)
            {
                if (_rfds[i].fd != defaultfd)
                    continue;
                else
                    break;
            }
            if (i == num)
            {
                logMessage(WARNING, "server is full, please wait");
                close(sock);
            }
            else
            {
                _rfds[i].fd = sock;
                _rfds[i].events = POLLIN;
                _rfds[i].revents = 0;
            }

            Print();
        }
        void Recver(int pos)
        {
            // 一定能读完吗?                       // 能保证不被阻塞吗??
            // 需要通过协议来保证读到一个完整的报文! // 只能保证第一次不被阻塞, 如果使用while, 可能会在后面读取的时候被阻塞!!
            char buffer[1024];
            ssize_t s = recv(_rfds[pos].fd, buffer, sizeof(buffer), 0);
            // logMessage(DEBUG, "s : %d", s);
            if (s > 0)
            {
                buffer[s] = 0;
                logMessage(NORMAL, "client# : %s", buffer);
            }
            else if (s == 0)
            {
                close(_rfds[pos].fd);
                ResetItem(pos);
                logMessage(NORMAL, "client quit!");
                return;
            }
            else
            {
                close(_rfds[pos].fd);                
                ResetItem(pos);
                logMessage(ERROR, "errno: %d, %s", errno, strerror(errno));
                return;
            }
            // 2. 处理 TODO
            std::string response = _func(buffer);
            // 3. write bug!
            write(_rfds[pos].fd, response.c_str(), response.size());
        }
        void start()
        {
            // ?
            for (;;)
            {
                int timeout = 1000;
                int n = poll(_rfds, num, timeout);
                // logMessage(DEBUG, "n : %d", n);
                switch (n)
                {
                case 0:
                    logMessage(NORMAL, "timeout...");
                    break;
                case -1:
                    logMessage(WARNING, "poll error, code: %d, err string", errno, strerror(errno));
                    break;
                default:
                    // 有事件就绪 监听事件 和 正常IO事件
                    logMessage(NORMAL, "%d have events ready!", n);
                    HandlerEvent();
                    // HandlerEvent(wfds);
                    break;
                }
            }
        }
        ~PollServer()
        {
            if (_listensock < 0)
                close(_listensock);
            if (_rfds)
                delete[] _rfds;
        }

    private:
        int _port;
        int _listensock;
        struct pollfd *_rfds;
        func_t _func;
    };
}